import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { InjectionKey } from 'vue'
import { IuserInfo } from '@/api/types/common'
import { getItem, setItem } from '@/utils/storage'
import { USER, TOKEN } from '@/utils/constants'

// 类型补充声明

const state = {
  count: 1,
  isCollapse: false,
  token: getItem<{token: string}>(TOKEN),
  user: getItem<IuserInfo>(USER)
}

export type State = typeof state

// 定义 injection key  对应 容器
export const key: InjectionKey<Store<State>> = Symbol('store')

// 创建一个新的 store 实例
export const store = createStore<State>({
  state,
  mutations: {
    setIsCollapse (state, payload) {
      state.isCollapse = payload
    },
    setUser (state, payload) {
      state.user = payload
      setItem(USER, JSON.stringify(state.user))
    },
    setToken (state, payload) {
      state.token = payload
      setItem(TOKEN, JSON.stringify(state.token))
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
